<?php
namespace app\index\controller;

use think\Controller;
use app\index\common;
use think\Db;
use think\Paginator;
use think\Request;


/**
 * 产品逻辑类
 */
class Product extends Controller
{
    public $user_id = 0;
    public $user = array();
    public $check_date = 0;

    public function _initialize() {      
        parent::_initialize();
        if(session('?user'))
        {
            $user = session('user');
            $user = Db::table('users')->where("id", $user['id'])->find();
            session('user',$user);            
            $this->user = $user;
            $this->user_id = $user['id'];
            $this->assign('user',$user); //存储用户信息
            $this->assign('user_id',$this->user_id);
        }
    }
    
    /**
     * 2018-4-18 日期格式
     * 曹振威 开发人
     * 删除类目
     */
    public function systematics_delete() {
        $user_id = $this->user_id;
        $system_id = input('system_id');
        $id = input('id');
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$id){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        $row = Db::table('systematics')->where($where)->setField('state',1);
        if($row){
            $date = array('code'=>666,'msg'=>'删除类目成功','data'=>''); 
        }else{
            $date = array('code'=>20037,'msg'=>'删除类目失败','data'=>'');
        }
        return $date;
    }
    
    /**
     * 2018-4-17 日期格式
     * 曹振威 开发人
     * 添加/修改类目
     */
    public function systematics_add_edit(){
        $user_id = $this->user_id;
        $cate_id = input('cate_id');  // 一级分类id
        $brand_id = input('brand_id'); // 品牌id
        $systematics = input('title');
        $id = input('id');
        $system_id = input('system_id');
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$cate_id || !$systematics){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        
        $superior_gene = $cate_id.'-'.$brand_id;
        $systematics_insert = [
            'system_id' => $system_id,
            'superior_id' => $brand_id,
            'superior_gene' => $superior_gene,
            'title' => $systematics,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $where['system_id'] = $system_id;
        $where['id'] = $id;
        if($systematics_insert){
            if($id){
                // 编辑
                $row = Db::table('systematics')->where($where)->update($systematics_insert); 
            }else{
                // 添加
                $row = Db::table('systematics')->insert($systematics_insert);
            }
            
            if($row){
                $date = array('code'=>666,'msg'=>'操作类目成功','data'=>''); 
            }else{
                $date = array('code'=>20036,'msg'=>'操作类目失败','data'=>'');
            }
        }
        return $date;
    }
    
    /**
     * 2018-4-18 日期格式
     * 曹振威 开发人
     * 单个删除规格
     */
    public function standard_del() {
        $system_id = input('system_id');
        $id = input('id');
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$id){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        $row = Db::table('standard')->where($where)->setField('state',1);
        if($row){
            $date = array('code'=>666,'msg'=>'删除规格成功','data'=>''); 
        }else{
            $date = array('code'=>20035,'msg'=>'删除规格失败','data'=>'');
        }
        return $date;
    }
    
    /**
     * 2018-4-17 日期格式
     * 曹振威 开发人
     * 单个添加/修改规格
     */
    public function standard_add_eidt(){
        $user_id = $this->user_id;
        $system_id = input('system_id');
        $name = input('title');
        $systematics_id = input('systematics_id');
        $id = input('id');
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$name){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        $stand_insert = [
            'system_id' => $system_id,
            'systematics_id' => $systematics_id,
            'title' => $name,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $where['system_id'] = $system_id;
        $where['id'] = $id;
        if($id){
            // 编辑模式
            $row = Db::table('standard')->where($where)->update($stand_insert); 
        }else{
            // 添加模式
            $row = Db::table('standard')->insert($stand_insert);
        }
        if($row){
            $date = array('code'=>666,'msg'=>'操作成功','data'=>'');
        }else{
            $date = array('code'=>20034,'msg'=>'操作失败','data'=>'');
        }
        return $date;
    }
    
    /**
     * 
    * 2018-4-12 日期格式
    * 曹振威 开发人
    * 产品发布
     * @param Request $Request
     * @return 
     */
    public function add_edit_product() {
        $product_insert = array();
        $user_id = $this->user_id;
        $system_id = input('system_id');
        $business_id = Db::table('business')->where('business_id',$user_id)->field('id')->select();
        $id = input('id','');
        $product_name = input('post.product_name');
        $total_profit = input('post.total_profit',''); // 总利润
        $commission = input('post.commission','');  // 分佣比例
        $files = request()->file('image');  // 产品相册  保存一张主图在product表
        $is_new = input('post.is_new','');
        $is_hot = input('post.is_hot','');
        $is_recommend = input('post.is_recommend','');
        $price = input('post.price');  // 现价
        $original_price = input('post.original_price');
        $cost_price = input('post.cost_price');
        $peer_price = input('post.peer_price'); // 同行价
        $synopsis = input('post.synopsis',''); // 产品简介
        $details = input('details',''); // 产品图文详情   保存html标签
        $kd_type = input('post.kd_type'); // 运费类型 0：统一运费；1：运费模板
        $on_type = input('post.on_type',0); // 发布类型；0：放入仓库；1：立即上架
        $systematics_id = input('systematics_id');
        $standard_id = input('standard_id');
        $attr_title = input('attr_title/a');
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$business_id){
            $this->check_date = 1;
            $date = array('code'=>20020,'msg'=>'该用户是非商户','data'=>'');
        }elseif(!$product_name || !$files || !$systematics_id || !$price || !$original_price || !$cost_price || !$peer_price){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date === 1){
            exit(json_encode($date));
        }
         $product_img = array();
        if(is_array($files)){
            foreach ($files as $file){
                $product_img[] = common::picture($file);
            }
        }else{
            $product_img[] = common::picture($files);
        }
        
        $product_insert = [
            'systematics_id' => $systematics_id,
            'standard_id' => $standard_id,
            'product_name' => $product_name,
            'pic_url' => $product_img[0],
            'system_id' => $system_id,
            'business_id' => $business_id,
            'price' => $price,
            'original_price' => $original_price,
            'cost_price' => $cost_price,
            'peer_price' => $peer_price,
            'createtine' => date('Y-m-d H:i:s')
        ];
        
        if($kd_type == 0){
            $shipping = input('post.shipping');  // 统一运费
            $product_insert['fare'] = $shipping;
        }elseif($kd_type == 1){
            $shipping = input('post.kd_module');  // 运费模板
            $product_insert['express_id'] = $shipping;
        }
        
        if($on_type == 0){
            $product_insert['is_shelf'] = 1;
        }elseif ($on_type == 1) {
            // 提交上架状态
            $product_insert['is_shelf'] = 2;
        }
        if($total_profit){
            $product_insert['total_profit'] = $total_profit;
        }
        if($commission){
            $product_insert['commission'] = $commission;
        }
        
        if($details){
            $product_insert['details'] = $details;
        }
        if($synopsis){
            $product_insert['synopsis'] = $synopsis;
        }
        if($id === ''){  // 添加模式
            $product_id = Db::table('product')->insertGetId($product_insert);
        }else{
            $product_id = $id;
            $where['product_id'] = $product_id;
        }
        
        if(!$product_id){
            $this->check_date = 2;
            $date = array('code'=>20022,'msg'=>'产品发布失败','data'=>'');
        }else{
            foreach ($product_img as $key=>$val){
                if($key != 0){
                    $img_insert[] = [
                        'product_id' => $product_id,
                        'pic_url' => $val,
                        'createtime' => date('Y-m-d H:i:s')
                    ];
                } 
                
            }
            if($id === ''){  // 添加模式
                $row_img = Db::table('productpic')->insertAll($img_insert);
            }else{
                foreach ($img_insert as $k_img => $v_img) {
                    $row_img = Db::table('productpic')->where($where)->update($v_img);
                }
            }
            
            if(!$row_img){
                $this->check_date = 2;
                $date = array('code'=>20023,'msg'=>'产品图片添加/更新失败','data'=>'');
            } else {
                if(is_array($standard_title)){
                    foreach ($standard_title as $k_stand => $v_stand) {
                        $standard_insert = [
                            'product_id' => $product_id,
                            'systematics_id' => $systematics_id,
                            'title' => $v_stand,
                            'createtime' => date('Y-m-d H:i:s')
                        ];
                        if($id === ''){
                            $row_standard = Db::table('standard')->insertGetId($standard_insert);
                        }else{
                            $row_standard = Db::table('standard')->where($where)->update($standard_insert);
                        }
                        if($attr_title){
                            if(is_array($attr_title)){
                                foreach ($attr_title as $k_attr => $v_attr) {
                                    $attr_insert[] = [
                                        'product_id' => $product_id,
                                        'standard_id' => $standard_id,
                                        'title' => $v_attr,
                                        'createtime' => date('Y-m-d H:i:s')
                                    ];
                                }
                                if($id === ''){
                                    $row_attr = Db::table('attributevalue')->insertAll($attr_insert);
                                }else{
                                    foreach ($attr_insert as $k_attribut => $v_attribut) {
                                        $row_attr = Db::table('attributevalue')->where($where)->update($v_attribut);
                                    }
                                }
                                if(!$row_attr){
                                    $this->check_date === 2;
                                    $date = array('code'=>20024,'msg'=>'产品属性添加失败','data'=>'');
                                }
                            }
                       }   
                    }
                }
            }
        }
        if($this->check_date === 2){
            exit(json_encode($date));
        }
       $date = array('code'=>666,'msg'=>'产品发布/编辑成功','data'=>'');
       return $date;
    }
    
    /**
     * 2018-4-10 日期格式
     * 曹振威 开发人
     * 产品删除/下架
     */
    public function operat_product() {
        $user_id = $this->user_id;
        $user_id = 1;
        $system_id = input('system_id','');
        $business_id = Db::table('business')->where('business_id',$user_id)->field('id')->select();
        $ids = input('post.id');
        $type = input('post.type'); // 1:下架；2：删除
        if(!$system_id){
            $this->check_date = 1;
            $date = array('code'=>20019,'msg'=>'没有此系统','data'=>'');
        }elseif(!$business_id){
            $this->check_date = 1;
            $date = array('code'=>20020,'msg'=>'该用户是非商户','data'=>'');
        }elseif(empty($ids) || empty($type)){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        
        $product_ids = explode(",",$ids);
        $where = [
            'system_id' => $system_id,
            'business_id' => $business_id,
        ];
        $product_up = [
            'is_shelf' => 1,
            'createtine' => date('Y-m-d H:i:s')
        ];
        if($type == 1){
            //下架
            Db::startTrans();//开启事务
            try{
                 $product_id = Db::table("product")->lock(TRUE)->where([
                     "id"=>["in",[$product_ids]]
                 ])->field("id")->select();
         print_r($product_id);die;
                Db::table("product")->where(["business_id"=>$user_id])->whereIn('id',$product_ids)->update($product_up);
                // 提交事务
                Db::commit();
                $date = array('code'=>666,'msg'=>'商品下架成功','data'=>'');
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                $date = array('code'=>20038,'msg'=>'商品下架失败','data'=>'');
            }
            
        }elseif($type == 2){
           // 删除 
            Db::table("product")->where(["business_id"=>$user_id])->whereIn('id',$product_ids)->update(['state'=>1,'createtine' => date('Y-m-d H:i:s')]);
            Db::table("review")->where(["business_id"=>$user_id])->whereIn('product_id',$product_ids)->update(['state'=>1,'createtine' => date('Y-m-d H:i:s')]);  //商品评论
            Db::table("productpic")->where(["business_id"=>$user_id])->whereIn('product_id',$product_ids)->update(['state'=>1,'createtine' => date('Y-m-d H:i:s')]);  //商品图片
            Db::table("standard")->where(["business_id"=>$user_id])->whereIn('product_id',$product_ids)->update(['state'=>1,'createtine' => date('Y-m-d H:i:s')]);  //商品规格
            $date = array('code'=>666,'msg'=>'删除商品成功','data'=>'');
        }
        return $date;
    }
    
    /**
     * 2018-4-11 日期格式
     * 曹振威 开发人
     * 产品列表
     */
    public function product_list() {
        //产品状态   仓库中  已售完  出售中
        $where = ' 1 = 1 ';
        $user_id = $this->user_id;
        $system_id = input('system_id');
        $business_id = Db::table('business')->where('business_id',$user_id)->field('id')->find();
        $page_current = input('page'); // 当前页
        $where = [
            'state' => 0,
            'business_id' => $business_id['id'],
            'system_id' => $system_id
        ];
        $count = Db::table('product')->where($where)->count();   // 满足条件的总条数
        //分页
        if($count>0){
            $product_list = Db::table('product')->where($where)->field('pic_url,id,is_shelf,product_name,price,stock,peer_price,product_sn,createtine')->paginate();
            $data = json_decode(json_encode($product_list));
            $last_page = $data->last_page; // 总页数
            if($page_current>$last_page){
                $date = array('code'=>20026,'msg'=>'没有这么多页哦','data'=>'');
            }else{
                $date = array('code'=>666,'msg'=>'产品列表获取成功','data'=>$product_list);
            }
        }else{
            $date = array('code'=>20027,'msg'=>'没有获取到产品','data'=>'');
        }
        return $date;
    }
    
    
    /**
     * 2018-4-12 日期格式
     * 曹振威 开发人
     * 产品信息详情
     */
    public function product_info(){
        $product_id = input('id');
        $where['id'] = $product_id;
        $where['state'] = 0;
        $product_info = Db::table('product')->where($where)->field('pic_url,id,is_shelf,product_name,price,peer_price,product_sn,createtine')->find();
        if($product_info){
            $date = array('code'=>666,'msg'=>'产品信息获取成功','data'=>$product_info);
        } else {
            $date = array('code'=>20028,'msg'=>'产品信息获取失败','data'=>'');    
        }
        return $date;
    }
}
